// pages/home/productDetails/productDetails.js
var app = getApp()
import userIndex from '../../../api/user';
import Index from '../../../api/index';
import shopCar from '../../../api/shopCar';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isPhone:app.globalData.isPhone,
    headerHeight:app.globalData.headerHeight,
    isIphoneX:app.globalData.isIphoneX,
    indicatorDots: true,
    vertical: true,
    autoplay: true,
    interval: 2000,
    duration: 500,
    modelPhone:false,

    servicetimeInterval:'',
    systimestamp:'',
    id:'',
    carNum:0,

    productInfo:null,
    introduction:'',


    showOrderModel:false,
    typesof:1,//1，加入购物车，2,立即购买,3试样

    type:1,//1:产品,2:试样,3:多规格
    num:1,
    skuId:'',
    skuInfor:'',
    productBuyInfo:[],

    typeList:[],//类型
    typeName:'',
    skuList:[],//规格
    skuName:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.setData({
      id:options.id
    })
    this.getProductInfo()
    this.getProductBuyInfo()
  },
  //购买广播
  getProductBuyInfo(){
    Index.apiProductBuyInfo({productId:this.data.id}).then(res=>{
      this.setData({
        productBuyInfo:res.data
      })
    })
  },
  //产品详情
  getProductInfo(){
    var that=this
    var opt={
      id:this.data.id
    }
    Index.apiProductInfo(opt).then(res=>{
      var productInfo=res.data
      productInfo.img=productInfo.img.split(',')
      var typeList=[]
        var skuList=[]
        var skuId=''
        var skuInfor=''
        var typeName=''
        var skuName=''
      if(productInfo.skuEnabel==1&&productInfo.skuList&&productInfo.skuList.length>0){
        
         skuList=productInfo.skuList.map(row=>{
          if(row.typeName){
            typeList.push(row.typeName)
          }
            return row.skuName
        })
        skuId=productInfo.skuList[0].id
        skuInfor=productInfo.skuList[0]
        skuName=productInfo.skuList[0].skuName
        typeName=productInfo.skuList[0].typeName
      }
      

        this.setData({
          productInfo:productInfo,
          typeList:Array.from(new Set(typeList)),
          skuList:Array.from(new Set(skuList)),
          skuId:skuId,
          skuInfor:skuInfor,
          skuName:skuName,
          typeName:typeName,
        })

        if(productInfo.seckillEndTime){
          var serverLocalDate = new Date().getTime();
          //调用函数开始计时
          this.serverLocalDate(serverLocalDate);
        }
        //富文本
        if(productInfo.contentUrl){
          that.getRichText(productInfo.contentUrl)
        }
    })
  },
  //富文本
getRichText:function(contentUrl){
  var that=this
  var content=contentUrl
  content=content.replace(/http:/g,'https:')
  wx.request({
    url: content, //仅为示例，并非真实的接口地址
    method:'get',
    success (res) {
      var richTextData=res.data
        richTextData=richTextData.replace(/<!DOCTYPE html>/g,'')
        richTextData=richTextData.replace(/<html lang="en">/g,'')
        richTextData=richTextData.replace(/<head>/g,'')
        richTextData=richTextData.replace(/<meta charset="utf-8">/g,'')        
        richTextData=richTextData.replace(/<meta http-equiv="X-UA-Compatible" content="IE=edge">/g,'')
        richTextData=richTextData.replace(/<meta name="viewport" content="width=device-width">/g,'')
        richTextData=richTextData.replace(/<meta name="viewport" content="width=device-width,initial-scale=1.0">/g,'')
        richTextData=richTextData.replace(/<\/head>/g,'')
        richTextData=richTextData.replace(/<style>\*%7Bmargin:0px;padding:0px;font-size:16px%7Dimg%7Bwidth:100%25%7D<\/style>/g,'')
        richTextData=richTextData.replace(/<style>\*{margin:0px;padding:0px;font-size:16px}img{width:100%}<\/style>/g,'')
        richTextData=richTextData.replace(/<body>/g,'')
        richTextData=richTextData.replace(/<body>/g,'')
        richTextData=richTextData.replace(/<\/body><\/html>/g,'')
        richTextData=richTextData.replace(/<img/g,'<img style="width:100%;display:black"')

        
        that.setData({
          introduction:richTextData
        })
    }
  })
},
getShopCarNum(){
  shopCar.apishopCarNum().then(res=>{
    this.setData({
      carNum:res.data?res.data.num:0,
    })
  })
},
//显示弹窗
openModel(e){
  if(!this.data.isPhone){
    this.getLoginBtn()
    return false
  }

  var typesof=e.currentTarget.dataset.typesof
  var productInfo=this.data.productInfo
  var skuId='',skuInfor='',typeName='',skuName=''
  var type=1
  if(typesof==3){
    type=2
  }else{  
      if(productInfo.skuEnabel==1){
        type=3
        if(productInfo.skuList){
          skuId=productInfo.skuList[0].id
          skuInfor=productInfo.skuList[0]
          typeName=productInfo.skuList[0].typeName
          skuName=productInfo.skuList[0].skuName
        }        
      }else{
        type=1
      }
  }
  
  this.setData({
    showOrderModel:true,
    typesof:typesof,
    type:type,
    skuId:skuId,
    skuInfor:skuInfor,
    skuName:skuName,
    typeName:typeName
  })
},
closeModel(){
  this.setData({
    showOrderModel:false,
    num:1,
    skuId:'',
    skuInfor:'',
  })
},
getsku(e){
  var item=e.currentTarget.dataset.item
 console.log(item,'itemitemitemitemitem')
  this.setData({
    skuName:item,
  })
  this.setSkuInfor()
},
getTypeName(e){
  var item=e.currentTarget.dataset.item
 
  this.setData({
    typeName:item,
  })
  this.setSkuInfor()
},
setSkuInfor(){
  var productInfoSkuList = this.data.productInfo.skuList
  var typeList=this.data.typeList
  var skuName=this.data.skuName
  var typeName=this.data.typeName
  var skuInfor=''
  if(typeList&&typeList.length>0){
    productInfoSkuList.forEach(element => {
      if(skuName==element.skuName&&typeName==element.typeName){
        skuInfor=element
      }
  });
  }else{
    productInfoSkuList.forEach(element => {
        if(skuName==element.skuName){
          skuInfor=element
        }
    });

  }
  console.log(skuInfor)
  this.setData({
    skuInfor:skuInfor,
    skuId:skuInfor.id,
  })
},

less(){
var num=this.data.num
if(num>0){
  num=num-1
}else{
  num=0
}
this.setData({
  num:num
})
},
add(){
  var num=this.data.num
  
  if(this.data.productInfo.limitEnabel==1){
    // 限购
    var limitNumber=this.data.productInfo.limitNumber
    if(this.data.type!=2){
      //不试样
      if(this.data.type==1){
        var reserve=this.data.productInfo.reserve||0 
      }else{
        //多规格
        var reserve=this.data.skuInfor.reserve||0 
      }
      if(num<limitNumber&&num<reserve){
        num=num+1
      }

    }else{
       //试样
      var sampleReserve=this.data.productInfo.sampleReserve
      if(num<limitNumber&&num<sampleReserve){
        num=num+1
      }

    }

  }else{
    //不限购
    if(this.data.type!=2){
      //不试样
      if(this.data.type!=2){
        //不试样
        if(this.data.type==1){
          var reserve=this.data.productInfo.reserve
        }else{
          //多规格
          var reserve=this.data.skuInfor.reserve
        }
        if(num<reserve){
          num=num+1
        }

    }else{
       //试样
      var sampleReserve=this.data.productInfo.sampleReserve
      if(num<sampleReserve){
        num=num+1
      }

    }
  }
}
this.setData({
  num:num
})
},
sureBtn(){
  if(!this.data.isPhone){
    this.getLoginBtn()
    return false
  }
  if(this.data.typesof!=2){
    this.addshopCar()
  }else{
    var productInfo=this.data.productInfo
    var skuInfor=this.data.skuInfor
    var data=[]
    var info={
      carId:'',
      contentUrl: productInfo.contentUrl,
      createTime: productInfo.createTime,
      img: productInfo.img[0],
      num: this.data.num,
      originalPrice: productInfo.originalPrice,
      price: productInfo.price,
      productId: productInfo.id,
      skuId: this.data.skuId||'',
      skuName: productInfo.skuName,
      tag:productInfo.tag,
      title:productInfo.title,
      type:this.data.type,
      typeName: this.data.typeName||'',
    }
    if(this.data.skuId){
      info.originalPrice=skuInfor.originalPrice
      info.price=skuInfor.price
      info.skuName=skuInfor.skuName
    }
    data.push(info)
    if(this.data.num==0){
      wx.showToast({
        title: '购买数量不能为0',
        icon:'none'
      })
      return false
    }
    
    wx.setStorageSync('shopCartList', data)
    wx.navigateTo({
      url: '/pages/home/orderConfirm/orderConfirm',
    })
  }
},
getLoginBtn(){
  this.setData({
    modelPhone:true,
  })
},
closeLoginBtn(){
  this.setData({
    modelPhone:false,
  })
},
getPhoneNumber(e){
  var code=e.detail.code
  if(code){
    userIndex.apigetPhone({code:code}).then(res=>{
      app.globalData.isPhone=res.data.phone?true:false
      this.setData({
        isPhone:res.data.phone?true:false,
        modelPhone:false,
      })
      this.getShopCarNum()
    })
  }
  
},
//添加购物车
addshopCar(){
  var opt={
    num:this.data.num,
    productId:this.data.id,
    type:this.data.type,
  }
  if(this.data.skuId){
    opt.skuId=this.data.skuId
  }
  shopCar.apishopCartSave(opt).then(res=>{
    wx.showToast({
      title: '已加入购物车',
    })
    this.closeModel()
    this.getShopCarNum()
  })
},
viewImage(){
  wx.previewImage({
    current: this.data.productInfo.img[0], // 当前显示图片的链接
    urls: this.data.productInfo.img // 需要预览的图片链接列表
  });
},
previewImage(e){
  console.log(e)
},
shopCaart(){
wx.navigateTo({
  url: '/pages/shopCart/index/index',
})
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if(this.data.isPhone){
      this.getShopCarNum()
    }
    
  },
   //服务器系统时间开始计时
   serverLocalDate: function (serverLocalDate) {
    console.log(serverLocalDate)
    var _this = this;
    let newDate = serverLocalDate;
    _this.setData({
      servicetimeInterval: setInterval(function () { // 循环执行  
        newDate = (newDate / 1000 + 1) * 1000;
        _this.setData({
          systimestamp: newDate
        })
      }, 1000)  // 每秒执行一次以达到更新时间的目的
    })
  },

  //收藏
  getViewcollectSave(e){
    userIndex.apiViewcollectSave({productId:this.data.id}).then(res=>{
      this.getProductInfo()
    })
  },
  //删除收藏
  getViewcollectDelete(){
    userIndex.apiViewcollectDelete({ids:this.data.id}).then(res=>{
      this.getProductInfo()
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    clearInterval(this.data.servicetimeInterval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    clearInterval(this.data.servicetimeInterval)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var userId=wx.getStorageSync('userInfo')?wx.getStorageSync('userInfo').userId:''
    return {
      title: this.data.productInfo.title, // 分享标题
      path: `/pages/home/productDetails/productDetails?referrerId=${userId}&id=${this.data.id}`, // 分享路径，必须是已经存在的页面路径
      // imageUrl: 'https://example.com/share.jpg', // 分享图标
      success: function (res) {
        // 转发成功
        if (res.errMsg === 'shareAppMessage:ok') {
          console.log('分享成功');
        }
      },
      fail: function (res) {
        // 转发失败
        console.log('分享失败', res);
      }
    }
  },
  onShareTimeline() {  
    var userId=wx.getStorageSync('userInfo')?wx.getStorageSync('userInfo').userId:''
    return {
      title: this.data.productInfo.title, // 分享标题
      path: `/pages/home/productDetails/productDetails?referrerId=${userId}&id=${this.data.id}`, // 分享路径，必须是已经存在的页面路径
      // imageUrl: 'https://example.com/share.jpg', // 分享图标
      success: function (res) {
        // 转发成功
        if (res.errMsg === 'shareAppMessage:ok') {
          console.log('分享成功');
        }
      },
      fail: function (res) {
        // 转发失败
        console.log('分享失败', res);
      }
    }
  } 
})